// 引入库
import axios from 'axios'
import { Message } from 'element-ui'
import Qs from 'qs'
import store from '@/store'
import { getToken } from '@/utils/auth'
// 创建公共请求实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})
let newtimeOut

// 请求拦截器
service.interceptors.request.use(
  config => {
    if (newtimeOut) {
      console.log('eeee')
      return
    }
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    config.data = Qs.stringify(config.data)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }

  // 此项目不需要请求拦截器

  // config => {
  //   // 请求中添加token
  //   // token固定格式
  //   // 当前校验 jwt bearer token
  //   if (store.getters.token) {
  //     config.headers.Authorization = 'Bearer ' + store.getters.token
  //   }
  //   // 如果没有token 说明是第一次发请求登录 必须放行
  //   return config
  // },
  // err => {
  //   return Promise.reject(new Error(err.message))
  // }
)

// 响应拦截器
service.interceptors.response.use(
  res => {
    console.log('ressss', res)
    // 这里是网络请求成功的部分
    const { msg, code } = res.data
    if (code === 0) {
      console.log(res, 'code === 0')
      return res
    } else if (code === 1) {
      return res
    } else {
      // 网络失败
      Message.error(msg)
      // return Promise.reject(new Error(msg))
      Message.error(new Error(msg))
      // console.log('失败了', msg)
    }
  },
  err => {
    console.log('error.response.status', err)
    // console.log(res)
    // 这里是网络层面的失败
    // console.log('这里是网络层面的失败', err)
    if (err.response.status === 401) {
      store.dispatch('user/logout')
      if (newtimeOut) {
        return
      }
      newtimeOut = setTimeout(async() => {
        // await store.dispatch('user/logout')
        // 清理token
        // store.commit('removeToken')
        // store.commit('removeuser')
        // store.commit('setgetSelect')
        store.dispatch('user/removeToken')
        // store.commit('deletedDatas')
        // resetRouter()
        // // 清空database里面的内容
        store.dispatch('database/deletedData', [], { root: true })
        // // 清空management里面的数据
        store.dispatch('management/removemanagement', [], { root: true })
        // 清空medicalDetails里面的数据
        store.dispatch('medicalDetails/deletedDatas', [], { root: true })
        // loglevel:webpack-dev-server
        // 清理缓存
        // sessionStorage.clear()
        window.localStorage.removeItem('loglevel:webpack-dev-server')
        window.localStorage.removeItem('database_id')
        window.localStorage.removeItem('getSelect')
        window.localStorage.removeItem('vuex')
        window.localStorage.removeItem('token')
        window.localStorage.removeItem('userinfo')

        localStorage.clear()
        await Message.error('身份验证失败，请重新登录')
        await history.go(0)
      })
    } else if (err.response.status === 403) {
      Message.error('你没有权限访问')
      // history.go(0)
    } else {
      // console.log('没进来')
      // 这里弹出错误提示
      Message.error('操作失败')
      history.go(0)
      return Promise.reject(new Error(err.msg))
    }
  }
)

export default service
